<template>
  <el-menu active-text-color="#ffd04b" background-color="#222727" class="el-menu-vertical-demo"
    :default-active="checkedTab.tabName" text-color="#fff" unique-opened>
    <el-menu-item index="首页&joint&Desktop" @click="handleMenuItemClick">
      <el-icon><icon-menu /></el-icon>
      <span>首页</span>
    </el-menu-item>
    <el-sub-menu v-for="menu in menuInfos" :index="menu.menuId" :key="menu.menuId">
      <template #title>
        <el-icon><location /></el-icon>
        <span>{{ menu.menuName }}</span>
      </template>
      <el-menu-item-group>
        <el-menu-item v-for="itemGroup in menu.submenus" :key="itemGroup.menuId" :index="getMenuItemIndex(itemGroup)"
          @click="handleMenuItemClick">{{ itemGroup.menuName }}</el-menu-item>
      </el-menu-item-group>
    </el-sub-menu>
  </el-menu>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'; // 导入 PropType
import type { PropType } from 'vue';
import { storeToRefs } from 'pinia';
import { homeStore } from '@/pinia/homeStore';
import { Document, Menu as IconMenu, Location, Setting } from '@element-plus/icons-vue';

const emits = defineEmits(['change']);
const homePinia = homeStore();
const { checkedTab } = storeToRefs(homePinia);

interface MenuItem {
  menuId: number; 
  menuPath: string;
  menuName: string;
  submenus?: MenuItem[];
  menuType: string;
  parentId: number;
  menuIcon: string;
}

const props = defineProps({
  menuInfos: {
    type: Array as PropType<MenuItem[]>, // 明确声明 menuInfos 的类型为 MenuItem[]
    default: () => [],
  },
});

const menuInfos = computed(() => {
  console.log('菜单组件-菜单列表', props.menuInfos);
  return props.menuInfos;
});

function getMenuItemIndex(itemGroup: MenuItem) {
  const pathSegments = itemGroup.menuPath ? itemGroup.menuPath.split('/') : [];
  return `${itemGroup.menuName}&joint&${pathSegments[pathSegments.length - 1]}`;
}

function traverseMenu(items: MenuItem[], str: string): MenuItem | null {
  for (const item of items) {
    const name = getMenuItemIndex(item);
    if (name === str) {
      return item;
    }
    if (item.submenus) {
      const result = traverseMenu(item.submenus, str);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

function handleMenuItemClick(el: { index: string }) {
  let menuItem: MenuItem = { menuId: -1, menuName: '首页', menuPath: 'Desktop', menuType: 'type', menuIcon: '',  parentId: -1};
  if (el.index !== '首页&joint&Desktop') {
    menuItem = traverseMenu(menuInfos.value, el.index) || menuItem;
  }
  emits('change', menuItem);
}
</script>

<style lang="scss" scoped>
.el-menu-vertical-demo {
  height: var(--max-height);
  padding: 8px;
  box-sizing: border-box;
}

.el-menu-item.is-active {
  background-color: var(--theme-primary);
  color: var(--main-white);
}
</style>

<style lang="scss">
.el-menu-vertical-demo .el-sub-menu .el-sub-menu__icon-arrow {
  font-size: 14px !important;
}
</style>
